<template>
  <a-modal v-model:open="open" :title="title" :confirm-loading="loading" @ok="submit" @cancel="cancel" width="550px">
    <a-form :model="form" :rules="rules" :label-col="{ sm: 4 }" ref="formRef">
      <a-form-item label="仓库类型" name="warehouse_type" required>
        <a-select v-model:value="form.warehouse_type" :options="warehouseTypeList" :disabled="form?.id" />
      </a-form-item>
      <template v-if="form.warehouse_type === 1">
        <a-form-item label="仓库属性" required name="attribute_type">
          <a-radio-group v-model:value="form.attribute_type" :options="attributeList" />
        </a-form-item>
      </template>
      <template v-if="form.warehouse_type === 2">
        <a-form-item label="负责人" required name="accountable">
          <a-cascader v-model:value="form.accountable" :disabled="form?.id" :options="accountableList" :field-names="{ label: 'name', value: 'id' }"></a-cascader>
        </a-form-item>
      </template>
      <a-form-item label="仓库名称" name="name" required>
        <a-input v-model:value.trim="form.name" placeholder="请输入仓库名称" />
      </a-form-item>
      <a-form-item label="仓库排序" name="sort">
        <a-input-number v-model:value="form.sort"></a-input-number>
      </a-form-item>
      <a-form-item label="仓库状态" name="status">
        <a-switch v-model:checked="form.status" :checkedValue="1" :unCheckedValue="2" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>
<script lang="ts" setup>
import _ from 'lodash'
import { message } from 'ant-design-vue'
import { searchApi } from '@/api/search/search-api'
import { warehouseApi } from '@/api/business/storage/warehouse-api'
import { WAREHOUSE_ATTRIBUTE_TYPE, WAREHOUSE_TYPE } from '@/constants/business/storage/warehouse/warehouse-const'
import { useEnums } from '@/hooks/plugins/useEnums'
import eventEmitter from '@/lib/event-emitter'
import customEventName from '@/views/business/storage/warehouse/warehouse/warehouse-event-name'
const { getValueDesc } = useEnums()

const open = ref(false)
const title = ref('新增仓库')
const loading = ref(false)
interface WarehouseFormParams {
  id?: number
  warehouse_type: number
  name: string
  path: string
  sort: number
  status: number
  accountable?: number[]
  accountable_id?: number
  accountable_type?: number
  attribute_type?: number
  code?: string
}
interface WarehouseFormModalProps {
  title: string
  data: WarehouseFormParams
}
eventEmitter.on(customEventName.WarehouseFormModal, (props: WarehouseFormModalProps) => {
  title.value = props.title
  form.value = _.cloneDeep(defaultForm)
  if (!_.isEmpty(props.data)) {
    const keys = _(form.value).keys().push('id').value()
    if (props.data.warehouse_type === WAREHOUSE_TYPE.FIXED.value) {
      keys.push('attribute_type')
    }
    if (props.data.warehouse_type === WAREHOUSE_TYPE.MOVE.value) {
      keys.push('accountable_id', 'accountable_type', 'code')
    }
    form.value = _.pick(props.data, keys) as WarehouseFormParams
    if (form.value.accountable_type && form.value.accountable_id) {
      form.value.accountable = [-form.value.accountable_type, form.value.accountable_id].map(Number)
    }
  }
  open.value = true
})

// 仓库属性
const warehouseTypeList = Object.entries(getValueDesc('WAREHOUSE_TYPE')).map(([value, label]) => ({ value: Number(value), label }))
const attributeList = Object.entries(getValueDesc('WAREHOUSE_ATTRIBUTE_TYPE')).map(([value, label]) => ({ value: Number(value), label }))

// 负责人
const accountableList = ref<any[]>([])
const getAccountableList = async (value: string) => {
  const { data: driverList } = await searchApi.driverList({ fields: 'id,name' })
  const { data: salesmanList } = await searchApi.salesmanList({ fields: 'id,rename' })
  accountableList.value = [
    {
      name: '司机',
      id: -2,
      children: driverList
    },
    {
      name: '业务员',
      id: -1,
      children: salesmanList.map(({ id, rename }) => ({ id, name: rename }))
    }
  ]
}
onMounted(getAccountableList)

// 提交
const formRef = ref()
const defaultForm = {
  warehouse_type: WAREHOUSE_TYPE.FIXED.value,
  name: '',
  path: '',
  sort: 0,
  status: 1,
  attribute_type: WAREHOUSE_ATTRIBUTE_TYPE.WAREHOUSE.value
}
const form = ref<WarehouseFormParams>(_.cloneDeep(defaultForm))
const rules = reactive({
  warehouse_type: [{ required: true, message: '请选择仓库类型', trigger: 'blur' }],
  name: [{ required: true, message: '请输入仓库名称', trigger: 'blur' }],
  accountable: [{ required: true, message: '请选择负责人', trigger: 'blur' }],
  attribute_type: [{ required: true, message: '请选择仓库属性', trigger: 'blur' }]
})
function submit() {
  if (unref(form).warehouse_type === WAREHOUSE_TYPE.MOVE.value && !unref(form)?.accountable[1]) {
    message.error('请选择司机')
    return
  }
  formRef.value.validate().then(async () => {
    const { accountable, ...param } = form.value
    const omitKey = param.warehouse_type === WAREHOUSE_TYPE.MOVE.value ? 'attribute_type' : ''
    const params = _.omit(param, omitKey)
    const fetchName = params.id ? 'update' : 'create'
    if (accountable) {
      params.accountable_id = accountable[1]
      params.accountable_type = Math.abs(accountable[0])
    }
    try {
      loading.value = true
      const res = await warehouseApi[fetchName](params)
      message.success(res.msg)
      eventEmitter.emit(customEventName.QueryWarehouseList)
      open.value = false
    } catch (error) {
      message.error(error.msg)
    } finally {
      loading.value = false
    }
  })
}
function cancel() {
  formRef.value.resetFields()
}
</script>
